<?php

#require_once 'Zend/Log.php';
require_once 'login/LoginRestParser.php';
require_once 'Zend/Json.php';

/**
 * Base class for parsing out a REST rest request.
 */
abstract class RestParser {

    /**
     * Associative array of the REST request parameters; path, operation, type, 
     * etc.
     */
    var $args = null;
    var $search = null;
    var $_timeLog = null;
    var $_auditLog = null;
    var $_startTime = null;
    var $_finishTime = null;
    /**
     * Associative array of valid REST operations.
     */
    protected $VALID_REST_ACTIONS = array(
    );

    /**
     * Sets the base value for the request arguments.
     * 
     * @param array $args The base request object; usually $_REQUEST.
     */
    function __construct($args) {
    	if (is_array($args)) {
    		$this->args = $args;
    	} else {
    		$this->args = array();
    	}    
    }

    /**
     * Returns an array of the valid REST actions.
     * 
     * @return array Valid REST actions.
     */
    public function getValidRestActions() {
        return $this->VALID_REST_ACTIONS;
    }

    public function parseRest(){
    	return $this->args;
    }
    
	public function dispatch($restParms){
		$action = $restParms['action'];
		if (!in_array($action, $this->VALID_REST_ACTIONS)){
			print "invalid action";
			return;
		}
		unset ($restParms['action']);
		$this->checkForAuth();
		try{
			$res = $this->handleAction($action, $restParms);
			$json = Zend_Json::encode($res);
			header('Content-type: application/json');
			print Zend_Json::prettyPrint($json, array("indent" => " "));
		} catch(Exception $e){
			print $e;
		}
	}
	
	abstract public function handleAction($action, $restParms);
	
	public function requiresAuth(){
		return true;
	}
	
	private function checkForAuth(){
		if ($this->requiresAuth()){
			$login = new LoginRestParser($this->args);
			$login->check();
		}
	}

}

?>
